<template>
  <a-card>
    <a-row :gutter="66">
      <a-col :span="9">
        <div class="table-operations">
          <a-button type="primary" @click="onAdd">新建</a-button>
        </div>
        <a-table
          bordered
          size="middle"
          :loading="loading"
          :columns="columns"
          :rowKey="(record) => record.id"
          :dataSource="data"
          @change="handleTableChange"
          :pagination="pagination"
        >
          <!-- table-row-operatiin -->
          <template v-slot:operation="record">
            <div class="table-row-operations">
              <a href="javascript:;" @click="onEdit(record)">修改 </a>
              <a-popconfirm title="Sure to delete?" @confirm="() => onDelete(record)">
                <a href="javascript:;">删除</a>
              </a-popconfirm>
            </div>
          </template>
        </a-table>
      </a-col>

      <a-col :span="15">
        <a-form layout="horizontal" :form="form">
          <a-form-item label="拥有权限">
            <a-row v-for="permission in permissions" :key="permission.permId">
              <a-col :xl="3" :lg="24" class="long-hide-text"> {{ permission.moduleName }}： </a-col>
              <a-col :xl="20" :lg="24">
                <a-checkbox :indeterminate="permission.indeterminate" :checked="permission.checkedAll" @change="onChangeCheckAll($event, permission)">
                  {{ permission.funsOptions.length > 0 ? '全选' : '查看' }}
                </a-checkbox>
                <a-checkbox-group :options="permission.funsOptions" v-model="permission.selected" @change="onChangeCheck(permission)" />
              </a-col>
            </a-row>
          </a-form-item>
        </a-form>
      </a-col>
    </a-row>
  </a-card>
</template>

<script>
const columns = [
  {
    title: '角色名',
    dataIndex: 'name',
    sorter: false
  },
  {
    title: '备注',
    dataIndex: 'remark',
    sorter: false
  },
  {
    title: '操作',
    key: 'operation',
    scopedSlots: { customRender: 'operation' }
  }
]

import initData from '@/mixins/initData'
import permission from '@/directive/permission' // 权限判断指令
import { get, del, getPermissions } from '@/api/role'

export default {
  name: 'Role',
  directives: { permission },
  mixins: [initData],
  data() {
    return {
      columns,
      autoExpandParent: true,
      checkedKeys: [],
      permissions: [],
      form: this.$form.createForm(this, { name: 'rolePermRel' })
    }
  },
  created() {
    this.$nextTick(() => {
      this.init()
      this.loadPermissions()
    })
  },
  watch: {
    checkedKeys(val) {
      console.log('onCheck', val)
    }
  },
  computed: {},
  methods: {
    beforeInit() {
      // ajax query
      this.url = 'oauth/role/page'
      this.params = { current: this.pagination.current, size: this.pagination.pageSize, sort: this.sort, ...this.query }
      return true
    },
    async loadPermissions() {
      const { data } = await getPermissions()
      data.forEach((e) => {
        e.checkedAll = false
        e.selected = []
        e.indeterminate = false
        e.funsOptions = e.funs.map((f) => ({ label: f.funName, value: f.permId }))
      })
      this.permissions = { ...data }
    },
    onChangeCheck(permission) {
      permission.indeterminate = !!permission.selected.length && permission.selected.length < permission.funsOptions.length
      permission.checkedAll = permission.selected.length === permission.funsOptions.length
    },
    onChangeCheckAll(e, permission) {
      console.log('permission:', permission)

      Object.assign(permission, {
        selected: e.target.checked ? permission.funsOptions.map((obj) => obj.value) : [],
        indeterminate: false,
        checkedAll: e.target.checked
      })
    },
    onAdd() {
      this.isAdd = true
      const _this = this.$refs['form']
      _this.getRoleSelect()
      _this.visible = true
    },
    async onEdit(record) {
      let res = await get(record.id)
      this.isAdd = false
      const _this = this.$refs['form']
      _this.getRoleSelect()
      _this.form = { ...res.data }
      _this.visible = true
    },
    async onDelete(record) {
      const key = 'delUser'
      try {
        this.$message.loading({ content: '正在删除...', key })
        let res = await del(record.id)
        this.$message.success({ content: '删除成功!', key, duration: 2 })
        this.init()
      } catch (err) {
        console.error(err.message)
      }
    }
  }
}
</script>
<style lang="less" scoped>
.long-hide-text {
  overflow: hidden; //超出隐藏
  text-overflow: ellipsis; // 省略号
  white-space: nowrap; //不换行
}
</style>
